#include "MoveTracker.h"

namespace Core
{

	MoveTracker::MoveTracker(void)
	
	{
		_head = -1;
	}


	MoveTracker::~MoveTracker(void)
	{
		for (int i = _moves.size() - 1; i >= 0; i--)
		{
			delete _moves[i];
			_moves.pop_back();
		}
	}

	int MoveTracker::moveCount() const
	{
		return _head + 1;
	}

	const Move * MoveTracker::at(int index) const 
	{
		if(index < 0 || index >= _moves.size())
			return NULL;
		return _moves.at(index);
	}

	Move * MoveTracker::last() const
	{
		if(_head == -1)
			return NULL;

		return _moves[_head];
	}

	int MoveTracker::newMove(const Move &mv)
	{
		// check validity of move
		Move * newMove = new Move(mv);
		Move::checkValidity(newMove);

		// delete move objects after the head (to prevent Redo expired move)
		for (int i = _moves.size() - 1; i > _head; i--)
		{
			delete _moves[i];
			_moves.pop_back();
		}

		_head++;
		_moves.push_back(newMove);

		return _head;
	}

	const Move * MoveTracker::undo()
	{
		if(_head < 0)
			return NULL;
		//_moves[_head]->piece()->undoMove();
		return _moves[_head--];	
	}

	const Move * MoveTracker::redo()
	{
		if(_head + 1 >= _moves.size())
			return NULL;

		//_moves[_head]->piece()->redoMove();
		return _moves[++_head];	
	}

	void MoveTracker::clear()
	{
		_head = -1;
		if(_moves.size() == 0)
			return;
		for (int i = _moves.size() - 1; i >= 0; i--)
			delete _moves[i];

		_moves.clear();
	}
}
